/**
 * extend loader
 * @params app koa实例
 * 加载所以 extend 可通过 'app.extend.${目录}.${文件}‘ 访问
 * 例子  extend 只有一层目录
 *   app/extend
 *     |
 *     |-- custom-extend
 *            
 * => app.extend.customExtend
 */

const { globSync } = require("glob");
const path = require("path");
const { sep } = path


module.exports = (app) => {
    // 读取app/extend/**/**.js 下面所有文件
    const extendPath = path.resolve(app.businessPath, `.${sep}extend`);
    const fileList = globSync(path.resolve(extendPath, `.${sep}**${sep}**.js`),{
        windowsPathsNoEscape:true
    });

    // 遍历文件，把内容加载到 app.extend下

    fileList.forEach(file => {
        let name = path.resolve(file)
        // 截取路径
        name = name.substring(name.lastIndexOf(`extend${sep}`) + `extend${sep}`.length, name.lastIndexOf('.'));
        // 把'-_',改成驼峰命名
        name = name.replace(/[_-][a-z]/ig, (s) => s.substring(1).toUpperCase())

        // 过滤 app 已经存在的key
        for (const key in app) {
            if (key === name) {
                console.log(`[extend loader error] name:${name} is exist `);
                return
            }
        }

        // 挂载 extend 到 app
        app[name] = require(path.resolve(file))(app)

    })


}